/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package common;

import BittorentPackage.BittorentPackageMessage;
import FolderChunks.FilenameChunk;
import FolderChunks.InfoChunk;
import java.awt.Component;
import java.util.ArrayList;
import managerPeer.Node;
import java.io.*;
import java.net.DatagramSocket;
import java.net.Socket;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author DongVan
 */
public class function_common {

    public static void infoBox(Component cp, String infoMessage, String location) {
        JOptionPane.showMessageDialog(cp, infoMessage, "InfoBox: " + location, JOptionPane.INFORMATION_MESSAGE);
    }
    //Read file txt  list peer

    public static BittorentPackageMessage deserializeBytes(byte[] bytes) throws IOException, ClassNotFoundException {
        ByteArrayInputStream bytesIn = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(bytesIn);
        Object obj = ois.readObject();
        ois.close();
        return (BittorentPackageMessage) obj;
    }

    public static byte[] serializeObject(Serializable obj) throws IOException {
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bytesOut);
        oos.writeObject(obj);
        oos.flush();
        byte[] bytes = bytesOut.toByteArray();
        bytesOut.close();
        oos.close();
        return bytes;
    }
    
    public static byte[] fileToArrayByte(File file) throws IOException {
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bytesOut);
        oos.writeObject(file);
        oos.flush();
        byte[] bytes = bytesOut.toByteArray();
        bytesOut.close();
        oos.close();
        return bytes;
    }
    
    public static ArrayList<String> readListFileDownload(String path) {
        ArrayList<String> list = null;
        try {
            BufferedReader input = new BufferedReader(new FileReader(path));
            list = new ArrayList<String>();
            String line = "";
            //line = input.readLine();
            while ((line = input.readLine()) != null) {
                list.add(line);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return list;
    }
    
    public static void writeListFileDownload(ArrayList<String> list, String path){
        try{
            BufferedWriter out = new BufferedWriter(new FileWriter(path));
            for(String str : list){
                out.write(str);
                out.newLine();
            }
            out.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    public static ArrayList<String> readListFileShare(){
        ArrayList<String> listFile = null;
        try{
            File files = new File(global.folderSharedPath);
            String[] names = files.list();
            listFile = new ArrayList<String>();
            for (String name : names) {
                listFile.add(name.replace(global.separatorBittorentTxt, "."));
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return listFile;
    }
    
    public static ArrayList<String> getAllFolder(String path)
    {
        ArrayList<String> list = new ArrayList<String>();
        File files = new File(global.folderSharedPath);
            String[] names = files.list();
            list = new ArrayList<String>();
            for (String name : names) {
                if(!name.contains("."))
                {
                    list.add(name);
                }
                else{
                    continue;
                }
            }
            return list;
    }
    
    public static FilenameChunk readChunkInfo(String path){
    
        FilenameChunk fileChunk = null;
        try{
            BufferedReader input = new BufferedReader(new FileReader(path));
            String line = "";
            fileChunk = new FilenameChunk();            
            InfoChunk info = null;
            //int index = 1;
            while((line = input.readLine())!= null){
                String [] lines = line.split(global.separatorBittorentTxt);
                info = new InfoChunk();
                info.setM_index(Integer.parseInt(lines[0]));
                info.setM_FileName(lines[1]);
                info.setM_HashValue(lines[2]);
                if(fileChunk.getM_Filename().equals("")){
                    fileChunk.setM_Filename(info.getM_FileName()); 
                }
                fileChunk.getM_ListChunk().add(info); 
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return fileChunk;
    }
    
    
    public static DefaultListModel<String> showArrayList(ArrayList<String> list){
        DefaultListModel<String> model = new DefaultListModel<String>();
        
        for(String item : list){
            model.addElement(item); 
        }
        return model;
    }

    public static void writeListFileShare(DefaultListModel<String> model) {
        try {
            BufferedWriter output = new BufferedWriter(new FileWriter("src\\FolderShareFile\\ListFileShare.txt"));
            for (int i = 0; i < model.size(); i++) {
                String line = model.getElementAt(i);
                output.write(line);
                output.newLine();
            }
            output.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static ArrayList<String> getListChunksOfFile(String folderName, boolean folderShared, boolean folderDownload) {
        ArrayList<String> myChunksKeeping = new ArrayList<>();
        String fileNameShared = global.folderSharedPath + "\\" + folderName;
        if (folderShared && checkAvailableFolder(fileNameShared)) {
            File files = new File(fileNameShared);
            String[] names = files.list();
            for (String name : names) {
                if (!myChunksKeeping.contains(name)) {
                    myChunksKeeping.add(name);
                }
            }
        }
        String fileNameDownloaded = global.folderDownloadPath + "\\" + folderName;
        if (folderDownload && checkAvailableFolder(fileNameDownloaded)) {
            File files = new File(fileNameDownloaded);
            String[] names = files.list();
            for (String name : names) {
                if (!myChunksKeeping.contains(name)) {
                    myChunksKeeping.add(name);
                }
            }
        }
        return myChunksKeeping;
    }
    
    public static boolean checkFolderContainChunksIsExists(String parentPath, String folderName) {
        String folderPathName = folderName;
        if (folderPathName.contains(".")) {
            String[] arrayFolderName = folderPathName.split(".");
            folderPathName = arrayFolderName[0];
        }
        File folderContainChunks = new File(parentPath + "\\" + folderPathName);
        if (!folderContainChunks.exists()) {
            return folderContainChunks.mkdir();
        }
        return true;
    }
    
    public static boolean checkAvailableFolder(String folderNamePath) {
        File folderChecked = new File(folderNamePath);
        return (folderChecked != null
                && folderChecked.exists()
                && folderChecked.canRead()
                && folderChecked.isDirectory()) ? true : false;
    }
    
    public static void ReceiveFile(String path , String fileName ,byte[] arrayByteReceive) throws InterruptedException{
       ByteArrayOutputStream arrayOutput = new ByteArrayOutputStream(); 
        
        if (arrayByteReceive != null) { 
            FileOutputStream fileOutput = null; 
            BufferedOutputStream bufferedOutput = null; 
            try { 
          
                Thread.sleep(800);
                fileOutput = new FileOutputStream(path+"\\"+fileName); 
                bufferedOutput = new BufferedOutputStream(fileOutput);    
                bufferedOutput.write(arrayByteReceive); 
                bufferedOutput.flush();
                bufferedOutput.close();
            } catch (IOException ex) {
            } 
        }
    }
    
}
